package ferp.android.ads.interstitial;

import android.content.Context;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import ferp.android.R;
import ferp.core.log.Log;

/**
 * User: olegs
 * Date: 14/07/2014 10:50
 */
public class AdmobInterstitialAdProvider implements InterstitialAdManager.Provider
{
  @Override
  public void load(Context context)
  {
    if (ia == null)
    {
      ia = new InterstitialAd(context.getApplicationContext());

      ia.setAdUnitId(context.getString(R.string.ad_id_admob));
      ia.setAdListener(new AdListener()
      {
        @Override
        public void onAdFailedToLoad(int errorCode)
        {
          Log.debug(Log.TAG, "Failed to load AdMob interstitial ad. Error code: " + errorCode);
        }

        @Override
        public void onAdLoaded()
        {
          Log.debug(Log.TAG, "AdMob interstitial ad loaded");

          loaded = true;
        }
      });
    }

    if (!loaded)
    {
      Log.debug(Log.TAG, "loading AdMob interstitial ad");

      ia.loadAd(request);
    }
  }

  @Override
  public void show()
  {
    if (ia != null)
    {
      if (ia.isLoaded())
      {
        Log.debug(Log.TAG, "AdMob interstitial shown");

        ia.show();
        loaded = false;
      }
      else
        Log.debug(Log.TAG, "AdMob interstitial not shown - not loaded yet");
    }
  }

  private static final AdRequest request = new AdRequest.Builder().build();

  private InterstitialAd ia;
  private boolean loaded;
}
